/*
	Get settings and update to local
*/
var settingsVM = function () {

	// Variables & localizations for Setting page
	var datacontext = new DataContext(),
	template = 'settingsTmpl',
	title = ko.observable(getLocalizeText('settings')),
	loginInformation = ko.observable(getLocalizeText('loginInformation')),
	cachedAbstract = ko.observable(getLocalizeText('cachedAbstract')),
	change = ko.observable(getLocalizeText('change')),
	logout = ko.observable(getLocalizeText('logout')),
	summaryDisplay = ko.observable(getLocalizeText('summaryDisplay')),
	bookSummaries = ko.observable(getLocalizeText('bookSummaries')),
	videoSummaries = ko.observable(getLocalizeText('videoSummaries')),
	english = ko.observable(getLocalizeText('english')),
	chinese = ko.observable(getLocalizeText('chines')),
	portuguese = ko.observable(getLocalizeText('portuguese')),
	german = ko.observable(getLocalizeText('german')),
	russian = ko.observable(getLocalizeText('russian')),
	spanish = ko.observable(getLocalizeText('spanish')),
	audioOnly = ko.observable(getLocalizeText('audioOnly')),
	videoOnly = ko.observable(getLocalizeText('video')),
	applyChanges = ko.observable(getLocalizeText('applyChanges')),
	strChange = ko.observable(getLocalizeText('change')),
	strEMail = ko.observable(getLocalizeText('eMail')),
	strPassword = ko.observable(getLocalizeText('password')),
	strOn = ko.observable(getLocalizeText('on')),
	strOff = ko.observable(getLocalizeText('off')),
	status = ko.observable(),
	list = ko.observableArray([]),
	settingsStatus = ko.observable(new SettingsModel()),

		// Hide/Show setting screen
		showSettingScreen = function (isDisplay) {
			if (document.getElementById('settingForm') != null) {
				if (isDisplay) {
					document.getElementById('settingForm').style.display = 'block';
				} else {
					document.getElementById('settingForm').style.display = 'none';
				}
			}
		},		

		// Show re-login page
		changeLoginInfo = function () {
			if (isLoading) {
				return;
			}
			model.viewLoginInformation();
		},

		// User logout
		clearCache = function () {
			if (!CanLoad())
				return;
			navigator.notification.confirm(
				getLocalizeText('doYouWantToLogout'), // message
				onConfirm, // callback to invoke with index of button pressed
				getLocalizeText('confirm'), // title
				getLocalizeText('ok') + ',' + getLocalizeText('cancel') // buttonLabels
			);
		},

		onConfirm = function (option) {
			var optionOk = 1;
			// [BB]
			if (isBB){
				optionOk = 0;
			}
			if (option == optionOk) {
				clearAllData();
				
			}
		},

		// Clear local storage. Keep: domainkey, wasrated, firstStart
		clearAllData = function () {
			/* keep some think before clear local data */
			ResetLocalStorage();
            
            model.startpageVM.startInfo(new StartModel());
            //overviewListFromSubcategory = new Array();
            model.startpageVM.isDisplayStartPage(true);
            showSettingScreen(false);
            stackViews = new Array();
            model.currentTab(startTab);
            model.tmpl('homeTmpl');
            $('.pt-page').removeClass('pt-page-absolute');
            model.homeVM.setLoginGUI();
            
            /* call logout api here, no need to receive result return */
            model.homeVM.logout();
		},

		// Submit changes in setting page
		applyChangeSettings = function () {
			updateSettingsToServer();
		},

		updateSettingsToServer = function () {
			if (!CanLoad())
				return;

			showLoadingDialog();
			isLoading = true;
			list([]);
			datacontext.setting.updateSetting({
				results: list,
				subData: getLanguageParam()
			}).done(function () {
				CheckExpireSession(
					list, 
					true,
					function() {
                        isUserActionClick = false;
						updateSettingsToServer();
					}, 
					function() {
                        getSettings(true);
						showPopup(getLocalizeText("applySettingsSuccessfull"));
					});
			}).fail(function (e) {
                    CheckExpireSessionErrorCallback(e,
                                                    function(){
                                                    /* session expired */
                                                    isUserActionClick = false;
                                                    updateSettingsToServer();
                                                    },
                                                    function(){
                                                    /* not expire */
                                                    
                                                    });
			});
		},

		getLanguageParam = function () {
			var lang = "";
			_.each(settingsStatus().summaryGroup(), function (i) {
                   var strLanguageCode = "";
                   _.each(i.languageOptions(), function (o) {
                          if ($('#lang' + i.id() + o.symbol()).val() == 'true'){
                          if (strLanguageCode == ""){
                          /* first time */
                          strLanguageCode = o.symbol();
                          }
                          else{
                          /* second time */
                          strLanguageCode += '-' + o.symbol();
                          }
                          }
                          });
                   console.log(lang);
                   if (strLanguageCode != ""){
                   if (lang == ""){
                   /* is first time */
                   lang = 'groups=' + i.id() + ':' + strLanguageCode;
                   }
                   else{
                   /* seond time */
                   lang += '&groups=' + i.id() + ':' + strLanguageCode;
                   }
                   
                   }
                   });
			return lang;
		},

		getLanguageString = function (isServer) {
			var lang = "";
            if (isServer){
                if (settingsStatus() != undefined){
                    _.each(settingsStatus().summaryGroup(), function (i) {
                           _.each(i.languageOptions(), function (o) {
                                  if (o.active() == true) {
                                  lang += o.symbol();
                                  }
                                  });
                           });
                }
                localStore.save(strSettingStringKey, lang);
            }
            else{
                if (localStore.get(strSettingStringKey) != undefined){
                    lang = localStore.get(strSettingStringKey);
                }
                else{
                    /* use default setting */
                    lang = systemLanguage;
                }
            }
			return lang;
		},

		// Change toggle ui elements
		updateSettingsUI = function () {
            if (settingsStatus() != undefined) {
				_.each(settingsStatus().summaryGroup(), function (i) {
                       _.each(i.languageOptions(), function (o) {
                              $('#lang' + i.id() + o.symbol()).val(o.active()+'').slider("refresh");
                                                            });
                       });
			}

		},

		getSettings = function (isServer) {
			var list = ko.observableArray([]);
			var entityTemp = new ko.observable(); //this parameter keep error model if any
            showLoadingDialog();
            isLoading = true;
			datacontext.getSetting.getSetting({
                results: list,
                key: 'saveFileSettingInfo',
                isServer: isServer,
                callbackFunc: function(){
                    stopLoading();
                    afterGetSetting(list()[0].object);
                }
            }).done(function () {
                if (list().length > 0){
                    CheckExpireSession(
                    list,
                    true,
                    function() {
                        getSettings(isServer);
                    },
                    function(entity) {

                        afterGetSetting(entity);
                        getLanguageString(true);
                    }
                    );
                }
            }).fail(function (e) {
                /* failed cause internet */
                    CheckExpireSessionErrorCallback(e,
                                                    function(){
                                                    /* session expired */
                                                    getSettings(isServer);
                                                    },
                                                    function(){
                                                    /* not expire */
                                                    
                                                    });
            });
		},
        afterGetSetting = function(settingObject){
            settingsStatus(settingObject);
            refreshLanguage();
            
            $('.settingslider').slider();
			updateSettingsUI();
            
            setTimeout(function(){
                       if (myScrollStart != null) {
                           myScrollStart.destroy();
                           myScrollStart = null;
                       }
                       if (isiOS || isBB || isAndroid) {
                       myScrollStart = new iScroll('wrapper_scrollview_setting', {
                                                   hideScrollbar: true,
                                                   hScroll: false
                                                   });
                       }
                       
                       },200);
        },
		back = function () {
			window.history.go(-1);
		},
		refreshLanguage = function () {
			title(getLocalizeText('settings'));
			loginInformation(getLocalizeText('loginInformation'));
			cachedAbstract(getLocalizeText('cachedAbstract'));
			change(getLocalizeText('change'));
			logout(getLocalizeText('logout'));
			summaryDisplay(getLocalizeText('summaryDisplay'));
			bookSummaries(getLocalizeText('bookSummaries'));
			videoSummaries(getLocalizeText('videoSummaries'));
			english(getLocalizeText('english'));
			chinese(getLocalizeText('chines'));
			portuguese(getLocalizeText('portuguese'));
			german(getLocalizeText('german'));
			russian(getLocalizeText('russian'));
			spanish(getLocalizeText('spanish'));
			audioOnly(getLocalizeText('audioOnly'));
			videoOnly(getLocalizeText('video'));
			applyChanges(getLocalizeText('applyChanges'));
			strChange(getLocalizeText('change'));
			strEMail(getLocalizeText('eMail'));
			strPassword(getLocalizeText('password'));
			strOn(getLocalizeText('on'));
			strOff(getLocalizeText('off'));
		};
		
	return {
		settingsStatus: settingsStatus,
		nameTmpl: template,
		title: title,
		loginInformation: loginInformation,
		cachedAbstract: cachedAbstract,
		change: change,
		logout: logout,
		summaryDisplay: summaryDisplay,
		bookSummaries: bookSummaries,
		videoSummaries: videoSummaries,
		english: english,
		chinese: chinese,
		portuguese: portuguese,
		german: german,
		russian: russian,
		spanish: spanish,
		audioOnly: audioOnly,
		videoOnly: videoOnly,
		applyChanges: applyChanges,
		showSettingScreen: showSettingScreen,
		changeLoginInfo: changeLoginInfo,
		clearCache: clearCache,
		applyChangeSettings: applyChangeSettings,
		getSettings: getSettings,
		getLanguageParam: getLanguageParam,
		getLanguageString: getLanguageString,
		updateSettingsUI: updateSettingsUI,
		back: back,
		strChange: strChange,
		strEMail: strEMail,
		strPassword: strPassword,
		strOn: strOn,
		strOff: strOff,
		refreshLanguage: refreshLanguage,
		clearAllData: clearAllData
	};
}()
